<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增供应商</el-button>
      </el-col>
      <el-col :span="20">
        <el-form :model="queryParams" ref="queryForm" :inline="true">
          <el-form-item label="供应商名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入供应商名称" clearable />
          </el-form-item>
          <el-form-item label="供应商分类" prop="categoryId">
            <el-select v-model="queryParams.categoryId" filterable clearable placeholder="请选择分类">
              <el-option v-for="(item) in providerCategoryList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="供应商状态" prop="status">
            <el-select v-model="queryParams.status" filterable clearable placeholder="请选择状态">
              <el-option v-for="(item) in providerStatusList" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-col>

    </el-row>
    <el-table v-loading="loading" :data="list">
      <el-table-column label="编号" align="center" prop="id" width="50" />
      <el-table-column label="供应商名称" align="center" prop="name" width="280" />
      <el-table-column label="供应商电话" align="center" prop="phone" width="180" />
      <el-table-column label=“供应商地址” align="center" prop="address" width="480" />
      <el-table-column label="供应商状态" align="center" prop="statusName" width="180" />
      <el-table-column label="供应商分类" align="center" prop="categoryName" width="180" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
      <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link size="small" type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link size="small" type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.size"
      @pagination="getProvidertLists" />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="dialogTitleText" v-model="open" width="600px" append-to-body @close="handleClose()">
      <el-form v-if="dialogTitleText == '编辑供应商' ? false : true" ref="addFormRef" :model="form" :rules="rules"
        label-width="120px">
        <el-form-item label="供应商名称:" prop="name">
          <el-input v-model="form.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="供应商电话:" prop="desr">
          <el-input v-model="form.phone" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="供应商地址:" prop="price">
          <el-input v-model="form.address" placeholder="请输入"></el-input>
        </el-form-item>

        <el-form-item label="供应商状态:" prop="status">
          <el-select v-model="form.status" filterable clearable placeholder="请选择状态">
            <el-option v-for="(item) in providerStatusList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商分类:" prop="cagegoryId">
          <el-select v-model="form.categoryId" filterable clearable placeholder="请选择类型">
            <el-option v-for="(item) in providerCategoryList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <el-form v-else ref="editFormRef" :model="editForm" :rules="rules" label-width="120px">
        <el-form-item label="供应商名称:" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="供应商电话:" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入商品描述"></el-input>
        </el-form-item>
        <el-form-item label="供应商地址:" prop="address">
          <el-input v-model="editForm.address" placeholder="请输入商品零售价"></el-input>
        </el-form-item>
        <el-form-item label="供应商分类:" prop="categoryId">
          <el-select v-model="editForm.categoryId" filterable clearable placeholder="请选择分类">
            <el-option v-for="(item) in providerCategoryList" :key="item.value" :label="item.label" :value="Number(item.value)">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商状态:" prop="status">
          <el-select v-model="editForm.status" filterable clearable placeholder="请选择状态">
            <el-option v-for="(item) in providerStatusList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer" v-loading="loading">
          <el-button @click="open = false">取 消</el-button>
          <el-button type="primary" @click="submitForm()">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import UpFile from "@/components/upFile/index.vue";
import { addFile, upFileReq, getImg, delFile } from "@/api/components/index.js";
import {
  getCategorylevel,
  editProduct,
  delProduct,
  getProviderList,
  addProvider,
  delProvider,
  editProvider
} from "@/api/product/index.js"
import { reactive } from "vue";

const { proxy } = getCurrentInstance();
const list = ref([]);
const open = ref(false);
const loading = ref(false);
const fileList = ref([]);
const upFileRef = ref(null);
const dialogTitleText = ref('')
const total = ref(0);
const providerCategoryList = ref([]);
const providerStatusList = ref([]);





let fileId;
const data = reactive({
  form: {
    name: '',
    phone: '',
    address: '',
    status: '',
    categoryId: ''
  },
  editForm: {
    name: '',
    phone: '',
    address: '',
    status: '',
    categoryId: '',
    id: ''
  },
  queryParams: {
    page: 1,
    size: 10,
    name: "",
    categoryId: "",
    status: ""
  }
});
const { editForm, form, queryParams } = toRefs(data);
function handleAdd() {
  open.value = true;
  dialogTitleText.value = '新增供应商'
  fileId = undefined;
  nextTick(() => {
    upFileRef.value.clearFiles();
  })
}
async function handleUpdate(row) {
  open.value = true;
  fileId = row.id;
  nextTick(() => {
    fileList.value = imgEvent(row);
  })
  dialogTitleText.value = '编辑供应商'
  editForm.value.name = row.name
  editForm.value.phone = row.phone
  editForm.value.address = row.address
  editForm.value.categoryId = row.categoryId
  editForm.value.status = row.status
  editForm.value.id = row.id



}
async function submitForm() {
  if (dialogTitleText.value !== '编辑供应商') {
    await proxy.$refs["addFormRef"].validate();
    // const imgRes = upFileRef.value.getFileRes();
    // if (imgRes.length === 0) return proxy.$modal.msgError("请上传商品图片");
    try {
      loading.value = true;
      const data = { ...form.value };
      !form.value.id && await addProvider({ ...data });
      // form.value.id&&await upUser(data);
      proxy.$modal.msgSuccess("新增成功");
      open.value = false;
      getProvidertLists();
    } finally {
      loading.value = false;
    }
  } else {
    // const imgRes = upFileRef.value.getFileRes();
    try {
      loading.value = true;
      const data = { ...editForm.value };
      !form.value.id && await editProvider({ ...data });
      // form.value.id&&await upUser(data);
      proxy.$modal.msgSuccess("修改成功");
      open.value = false;
      getProvidertLists();
    } finally {
      loading.value = false;
    }

  }

}
async function handleDelete(row) {
  await proxy.$modal.confirm("确认删除当前供应商吗？");
  await delProvider({ id: row.id });
  proxy.$modal.msgSuccess("删除成功");
  getProvidertLists();

}

function formatCategory(categoryId) {
  let foundLabel = null; // 初始化一个变量来存储找到的 label
  for (let i = 0; i < providerCategoryList.value.length; i++) {
    const ele = providerCategoryList.value[i];
    if (categoryId.toString() === ele.value) {
      foundLabel = ele.label; // 当找到匹配的项时，设置 foundLabel
      break; // 跳出循环
    }
  }
  return foundLabel; // 返回找到的 label，如果没有找到则返回 null
}
function formatStatus(status) {
  var result; // 定义一个变量来存储结果（如果找到的话）
  for (var i = 0; i < providerStatusList.value.length; i++) {
    var ele = providerStatusList.value[i]; // 获取当前元素
    if (status.toString() === ele.value) {
      result = ele.label; // 如果找到匹配的，将label赋值给result
      break; // 可以选择在这里使用break来退出循环，因为我们只需要第一个匹配的
    }
  }
  return result
}

async function getProvidertLists() {
  try {
    loading.value = true;
    await getProviderCategoryEnum()
    await getProviderStatusEnum()
    const { data, total: totalAll } = await getProviderList(queryParams.value);
    total.value = totalAll;
    list.value = data;
    list.value.map(ele => {

      ele.statusName = formatStatus(ele.status)
      ele.categoryName = formatCategory(ele.categoryId)

      return ele

    })
    console.log()
  } finally {
    loading.value = false;
  }
}

async function getProviderCategoryEnum() {
  try {
    const { data } = await getCategorylevel({ type: 'providerCategory' });
    providerCategoryList.value = data
    providerCategoryList.value.forEach(ele => {
      ele.label = ele.dictLabel
      ele.value = ele.dictValue
    })
  } finally {
  }
}
async function getProviderStatusEnum() {
  try {
    const { data } = await getCategorylevel({ type: 'providerType' });
    providerStatusList.value = data
    providerStatusList.value.forEach(ele => {
      ele.label = ele.dictLabel
      ele.value = ele.dictValue
    })
  } finally {
  }
}
function handleQuery() {
  queryParams.value.page = 1;
  getProvidertLists();
}
function imgEvent(row) {
  try {
    return JSON.parse(row.val)
  } catch (e) {
    return []
  }
}
function handleClose() {
  form.value = {}
}
// getImgApi();
getProvidertLists()

</script>

<style scoped lang="scss">
.flex-box {
  text-align: center;
}

.img-box {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  overflow: auto;

  >div {
    margin: 0 5px;
  }
}
</style>